package cn.topevery.garden.wapi.controller;

import cn.topevery.garden.dal.logic.ParkCompanyLogic;
import cn.topevery.garden.entity.impot.CompanyImportParam;
import cn.topevery.garden.entity.po.Company;
import cn.topevery.garden.entity.query.CompanyQuery;
import cn.topevery.garden.entity.vo.CompanyVO;
import cn.topevery.garden.wapi.utils.ExcelUtils;
import hw.topevery.basis.entity.po.SysUser;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.util.ExcelUtil;
import hw.topevery.framework.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;

/**
 * 企业管理
 *
 * @author code-generate
 * @date 2021-08-06
 */
@Api(tags = "企业管理接口")
@RestController
@RequestMapping("/company")
public class CompanyController extends BaseController {


    @Autowired
    ParkCompanyLogic companyLogic;

    /**
     * 获取分页列表
     *
     * @param query
     * @return
     */
    @ApiOperation(value = "获取页列表")
    @PostMapping("/listPage")
    public JsonResult<DataPager<Company>> listPage(@RequestBody CompanyQuery query) {
        return JsonResult.ok(companyLogic.listPage(query));
    }

    @ApiOperation("新增/编辑 信息")
    @PostMapping("/saveOrUpdate")
    //todo 【注】企业应当是pmi中部门的一种，c_company_id应对应t_sys_dept.c_dept_id,此处导入数据和新增数据存在问题
    public JsonResult saveOrUpdate(@Valid @RequestBody Company dto) {
        if (dto.getId() == null) {
            dto.setDbStatus(false);
            dto.setCompanyId(UUID.randomUUID().toString());
        }

        Integer userId = getUser().id;
        boolean isSave = companyLogic.saveOrUpdate(userId.toString(), dto);
        if (isSave) {
            return JsonResult.ok(true);
        } else {
            return JsonResult.error("保存失败");
        }
    }


    @ApiOperation("根据自增ID批量删除")
    @GetMapping("/deleteBatchById")
    public JsonResult<Boolean> deleteBatchById(@RequestParam Integer[] ids) {
        companyLogic.deleteBatchById(getUser().id.toString(), ids);
        return JsonResult.ok(true);
    }

    @ApiOperation("导出信息")
    @GetMapping("/export")
    public void export(CompanyQuery query, HttpServletResponse response) {
        List<Company> list = companyLogic.listPage(query).records;
        ExcelUtil.exportExcel(list, "", "sheet1", Company.class, "", response);
    }

    /**
     * 描述 检查导入数据.
     *
     * @param file the file
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-19 09:35:59 Analysis excel data json result.
     */
    @PostMapping("/analysisExcel")
    public JsonResult AnalysisExcelData(@RequestParam("file") MultipartFile file) {
        boolean isPass = true;
        String msg = "";
        List<CompanyVO> persons = null;
        try {
            persons = ExcelUtils.importExcel(file, 0, 1, CompanyVO.class);
        } catch (Exception e) {
            msg = "解析发生错误，请按照模板格式填写数据！";
            return JsonResult.error(msg);
        }

        List<CompanyVO> newData = new ArrayList<>();
        for (CompanyVO p : persons) {
            String anaylsisRes = "";
            if (p.getSid() == 0 && p.getName() == null) {
                break;
            }
            boolean isExists1 = companyLogic.isExit("c_name", p.getName());
            if (isExists1) {
                anaylsisRes += "企业名称与现有重复；";
            }
            boolean isExists2 = companyLogic.isExit("c_registration_code", p.getRegistrationCode());
            if (isExists2) {
                anaylsisRes += "企业信用代码与现有重复；";
            }

            if (anaylsisRes.length() > 0) {
                p.setPass(false);
                p.setAnalysisRes(anaylsisRes);
            } else {
                p.setPass(true);
                p.setAnalysisRes("验证通过");
            }
            newData.add(p);
        }
        isPass = !newData.stream().anyMatch(a -> a.isPass() == false);
        Map<String, Object> res = new HashMap<>();
        res.put("isPass", isPass);
        res.put("data", newData);
        return JsonResult.ok(res);
    }

    /**
     * 描述 导入数据.
     *
     * @param param the param
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-19 09:35:53 Import excel data json result.
     */
    //todo 【注】企业应当是pmi中部门的一种，c_company_id应对应t_sys_dept.c_dept_id,此处导入数据和新增数据存在问题
    @PostMapping("/importExcel")
    public JsonResult importExcelData(@RequestBody CompanyImportParam param) {

        SysUser user = getUser();
        if (param.getTableData() != null && param.getTableData().size() > 0) {

            for (CompanyVO p : param.getTableData()) {
                Company tmp = new Company();
                tmp.setCompanyId(UUID.randomUUID().toString());
                tmp.setDbStatus(false);
                tmp.setName(p.getName());
                tmp.setNameShort(p.getNameShort());
                tmp.setRegistrationCode(p.getRegistrationCode());
                tmp.setBuildTime(p.getBuildTime());
                tmp.setAddress(p.getAddress());
                tmp.setLowPeople(p.getLowPeople());
                tmp.setContacts(p.getContacts());
                tmp.setContactsPhone(p.getContactsPhone());
                tmp.setDescs(p.getDesc());

                companyLogic.saveOrUpdate(user.id.toString(), tmp);
            }
        } else {
            return JsonResult.error("导入数据列表不能为空");
        }
        return JsonResult.ok();
    }

    @ApiOperation("根据id查询企业下的所有用户")
    @GetMapping("/getUserInCompany")
    public JsonResult<?> getUserInCompany(@RequestParam Integer companyId) {
        return companyLogic.getUserInCompany(companyId);
    }
}
